<template>
  <div class="ModInfo">
    <h3>用户信息修改</h3>

    <div class="headImg">
      <img v-if="user.avatar" :src="dalImg(user.avatar)" @click="openFile"/>
      <img v-else src="../../assets/image/2124212.jpg" @click="openFile"/>
    </div>
    <input type="file" @change="changeImg" id="fileId" style="display: none" />
    <button class="changeBtn" @click="openFile">点击更换图像</button>
    <div class="ninike">
      昵称：<input type="text" v-model="aa" placeholder="请输入昵称" />
    </div>
    <button id="save" @click="save">保 存</button>
  </div>
</template>
<!-- js -->
<script setup>
import { ref } from "vue";
import { dalImg } from "../../utils/tools";
import { modifyUserInfoAPI, loadUserInfoAPI } from "../../services/auth";
import {Toast} from 'vant'
import { post } from "../../utils/request";
import { useRouter } from "vue-router";
const nickName = ref();
const defaultName = "开心";
let b = nickName ? nickName : defaultName;
const aa = ref(b);
const user = ref({});
const {push} = useRouter();

//点击显示图片选择页面
const openFile = () => {
  fileId.click();
};
loadUserInfoAPI().then((res) => {
  // console.log(res);
  user.value = res.data;
  // console.log(user.value);
  nickName.value = res.data.nickName;
});

//上传图片到服务器中
const changeImg = () => {
  const formData = new FormData();
  formData.append("file", fileId.files[0]);
  post("/api/v1/common/upload_file", formData).then((res) => {
      user.value.avatar=res.data;
  });
};

// //点击保存发送请求
const save = async () => {
   const params = `nickName=${nickName.value}&avatar=${user.value.avatar}`;
  const res = await modifyUserInfoAPI(params);
  // console.log(res);
  if (res.code == 1) {
    Toast({ message: "修改成功" });
    setTimeout(() => {
      push({name:'User'})
    }, 500);
  }
};
</script>
<!-- 样式 -->
<style scoped>
h3 {
  text-align: center;
  margin: 0.5rem;
}
.headImg {
  display: flex;
  width: 8rem;
  height: 8rem;
  border-radius: 50%;
  border: 1px solid #b8b3b3;
  margin: 4rem auto;
  overflow: hidden;
  align-items: center;
  justify-content: center;
}
img {
  height: 8rem;
  vertical-align: middle;
}

button {
  width: 16rem;
  height: 3rem;
  border: none;
  border-radius: 0.5rem;
  background-color: rgb(229, 226, 224);
  color: rgb(41, 40, 40);
  font-size: 1.2rem;
}
.changeBtn {
  display: block;
  margin: 0 auto;
}
.ninike {
  width: 20rem;
  height: 3rem;
  margin: 5rem auto;
}
input {
  /* display: block; */
  width: 16rem;
  height: 2.5rem;
  border: 1px solid #ababab;
  /* margin: 5rem auto; */
  text-indent: 1rem;
  font-size: 1.2rem;
}
#save {
  width: 16rem;
  height: 4rem;
  display: block;
  margin: 5rem auto;
  border: none;
  background-color: rgb(232, 31, 31);
  color: white;
  font-size: 1.1rem;
}
#save a {
  color: white;
}
</style>
